.<template>
  <div>
    <el-upload
      action="#"
      :file-list="fileList"
      list-type="picture-card"
      :on-preview="previewFn"
      :on-change="changeFn"
      :on-remove="removeFn"
      :class="{disble:fileList.length === 1}"
      :http-request="uploadFn"
      :before-upload="beforeUpload"
    >
      <i slot="default" class="el-icon-plus" />
    </el-upload>

    <el-progress
      v-if="showProgress"
      :percentage="percentage"
      :show-text="false"
      style="width:146px"
    />

    <el-dialog :visible="showDialog" title="预览" @close="showDialog = false">
      <el-row type="flex" justify="center">
        <img :src="imgUrl" alt="" width="100%">
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKID64nIdjaBWbQ0LQFqDLDpBG6i5FAqGRM2',
  SecretKey: 'UjiSwABxUlmX2HGyQecKmytZy73mJart'
})
export default {
  data() {
    return {
      fileList: [],
      showDialog: false,
      imgUrl: '',
      showProgress: false,
      percentage: 0
    }
  },
  methods: {
    //   点击已上传文件时
    previewFn(file) {
      this.showDialog = true
      //   console.log(file)
      this.imgUrl = file.url
    },
    // 文件改变时
    changeFn(file, fileList) {
    //   console.log(file)
      this.fileList = fileList
    },
    // 删除
    removeFn(file, fileList) {
    //   console.log(fileList)
      this.fileList = fileList
    },
    // 覆盖默认的上传行为，可以自定义上传的实现
    uploadFn(data) {
    //   console.log(data)
      this.showProgress = true
      cos.putObject({
        Bucket: 'ren-zi-xi-tong-1308775163', /* 填入您自己的存储桶，必须字段 */
        Region: 'ap-guangzhou', /* 存储桶所在地域，例如ap-beijing，必须字段 */
        Key: data.file.name, /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
        StorageClass: 'STANDARD',
        Body: data.file, // 上传文件对象
        onProgress: (progressData) => {
          console.log(JSON.stringify(progressData))
          this.percentage = progressData.percent * 100
        }
      }, (err, data) => {
        console.log(err || data)
        if (data) {
          this.fileList[0].url = 'http://' + data.Location
          this.fileList[0].status = 'success'
        //   console.log(this.fileList)
        }
        setTimeout(() => {
          this.showProgress = false
        }, 800)
      })
    },
    // 上传前校验
    beforeUpload(file) {
    //   console.log(file)
      const maxSize = 500 * 1024
      if (file.size > maxSize) {
        this.$message.warning('图片大小不能超过500k')
        return false
      }
      const imgType = ['image/jpeg', 'image/png']
      if (!imgType.includes(file.type)) {
        this.$message.warning('图片类型只能为jpeg或者png')
        return false
      }
    }
  }
}
</script>

<style lang='scss' scoped>
 .disble{
    ::v-deep .el-upload--picture-card{
            display: none;
    }
 }
</style>
